package controller;

import entity.Emp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class UploadController {

    @Autowired
    private ServletContext application;

    // @RequestMapping("/upload")
    // public String upload(@RequestParam("name") String name,
    //                      @RequestParam("file") CommonsMultipartFile file ) throws IOException {
    //     System.out.println("UploadController.upload()");
    //
    //
    //     System.out.println("name = " + name);
    //     System.out.println("file = " + file);
    //
    //     System.out.println("file.getName() = " + file.getName());
    //
    //     System.out.println("file.getOriginalFilename() = " + file.getOriginalFilename());
    //     System.out.println("file.getContentType() = " + file.getContentType());
    //     System.out.println("file.getSize() = " + file.getSize());
    //
    //     // file.getInputStream();
    //     // file.getResource();
    //
    //     // String updateDir=application.getRealPath("WEB-INF/upload");
    //
    //
    //
    //     String updateDir=this.getClass().getClassLoader().getResource("").getPath();
    //     updateDir=updateDir.substring(0,updateDir.lastIndexOf("/WEB-INF"))+"/WEB-INF/upload";
    //
    //     String fileName=file.getOriginalFilename();
    //
    //
    //
    //
    //
    //     file.transferTo(new File(updateDir,fileName));
    //
    //
    //
    //     return "redirect:/showUpload";
    // }


    @RequestMapping("/upload")
    public String upload(Emp emp,
                         @RequestParam("file") CommonsMultipartFile file ) throws IOException {
        System.out.println("UploadController.upload()");


        System.out.println("name = " + emp.getName());
        System.out.println("file = " + file);

        System.out.println("file.getName() = " + file.getName());

        System.out.println("file.getOriginalFilename() = " + file.getOriginalFilename());
        System.out.println("file.getContentType() = " + file.getContentType());
        System.out.println("file.getSize() = " + file.getSize());

        // file.getInputStream();
        // file.getResource();

        // String updateDir=application.getRealPath("WEB-INF/upload");



        String updateDir=this.getClass().getClassLoader().getResource("").getPath();
        updateDir=updateDir.substring(0,updateDir.lastIndexOf("/WEB-INF"))+"/WEB-INF/upload";

        String fileName=file.getOriginalFilename();





        file.transferTo(new File(updateDir,fileName));



        return "redirect:/showUpload";
    }


}
